<template>
	<picker class="form-item-picker" mode="multiSelector" @click="init" @change="changeAddress"
		@columnchange="columnChange" :value="cityIndex" :range="cityArray" range-key="name">
		<view class="region-value">{{cityValue}}</view>
	</picker>
</template>

<script setup>
	import geo from './geo.json'
	const { proxy } = getCurrentInstance()

	const props = defineProps({
		defaultIndex: {
			type: Array,
			default: () => [0, 0, 0]
		},
		defaultAddress: {
			type: String,
			default: ''
		}
	})

	const emits = defineEmits(['changeRegion'])

	const cityData = ref([])
	const cityArray = ref([[], [], []])
	const cityIndex = ref([...props.defaultIndex])
	const cityCode = ref('')
	const cityValue = ref(props.defaultAddress || '北京市市辖区东城区')

	onMounted(() => {
		init()
	})

	// 初始化数据
	const init = async () => {
		if (props.defaultIndex.length > 0) {
			cityIndex.value = [...props.defaultIndex]
		}
		
		const { provinceData, cityArray: initCityArray } = await getCityData()
		cityData.value = provinceData
		cityArray.value = initCityArray

		if (cityValue.value) {
			updateIndexByAddress(cityValue.value)
		}
	}

	// 根据地址更新索引
	const updateIndexByAddress = (address) => {
		const addressList = parseAddress(address)
		if (!addressList || addressList.length < 3) return

		const provinceIdx = findIndex(cityData.value, addressList[0])
		if (provinceIdx === -1) return

		const cityList = cityData.value[provinceIdx].children
		const cityIdx = findIndex(cityList, addressList[1])
		if (cityIdx === -1) return

		const areaList = cityList[cityIdx].children
		const areaIdx = findIndex(areaList, addressList[2])
		if (areaIdx === -1) return

		cityArray.value[1] = cityList
		cityArray.value[2] = areaList
		cityIndex.value = [provinceIdx, cityIdx, areaIdx]
	}

	// 解析地址字符串
	const parseAddress = (address) => {
		const specialRegions = {
			'北京市': /.+?(市|市辖区|区)/g,
			'天津市': /.+?(市|市辖区|区)/g,
			'上海市': /.+?(市|市辖区|区)/g,
			'重庆市': /.+?(市|市辖区|区)/g,
			'香港特别行政区': /.+?(行政区|香港|界|岛|龙|区)/g,
			'澳门特别行政区': /.+?(行政区|岛|区)/g
		}

		const province = address.substring(0, 6)
		const regex = specialRegions[province] || /.+?(省|市|自治区|自治州|行政区|县|区)/g
		return address.match(regex)?.slice(0, 3)
	}

	// 选择城市
	const changeAddress = (e) => {
		const [provinceIdx, cityIdx, areaIdx] = e.detail.value
		const [provinces, cities, areas] = cityArray.value
		
		const province = provinces[provinceIdx]
		const city = cities[cityIdx]
		const area = areas[areaIdx] || city
		
		cityValue.value = `${province.name}${city.name}${area?.name || ''}`
		cityCode.value = area?.code || city.code
		cityIndex.value = [provinceIdx, cityIdx, areaIdx]

		emits("changeRegion", {
			cityCode: cityCode.value,
			cityValue: cityValue.value,
			cityIndex: cityIndex.value
		})
	}
	
	// picker 列切换
	const columnChange = (e) => {
		const { column, value } = e.detail
		const newIndex = [...cityIndex.value]
		
		switch (column) {
			case 0:
				updateProvinceColumn(value)
				newIndex[0] = value
				newIndex[1] = 0
				newIndex[2] = 0
				break
			case 1:
				updateCityColumn(cityIndex.value[0], value)
				newIndex[1] = value
				newIndex[2] = 0
				break
			case 2:
				newIndex[2] = value
				break
		}
		
		cityIndex.value = newIndex
	}

	// 更新省份列
	const updateProvinceColumn = (provinceIdx) => {
		const province = cityData.value[provinceIdx]
		if (!province?.children) return
		
		cityArray.value[1] = province.children
		cityArray.value[2] = province.children[0]?.children || []
	}

	// 更新城市列
	const updateCityColumn = (provinceIdx, cityIdx) => {
		const city = cityData.value[provinceIdx]?.children[cityIdx]
		if (!city?.children) return
		
		cityArray.value[2] = city.children
	}

	// 获取城市数据
	const getCityData = () => {
		return new Promise((resolve) => {
			const provinceData = [...geo]
			const cityArrayData = [[], [], []]
			
			// 处理省份数据
			provinceData.forEach(province => {
				cityArrayData[0].push({
					code: province.code,
					name: province.name,
					province: province.province
				})
			})
			
			// 处理城市数据
			const defaultProvince = provinceData[cityIndex.value[0]]
			if (defaultProvince?.children) {
				cityArrayData[1] = defaultProvince.children.map(city => ({
					code: city.code,
					name: city.name,
					province: city.province,
					city: city.city
				}))
				
				// 处理区县数据
				const defaultCity = defaultProvince.children[cityIndex.value[1]]
				if (defaultCity?.children) {
					cityArrayData[2] = defaultCity.children.map(area => ({
						code: area.code,
						name: area.name,
						province: area.province,
						city: area.city,
						area: area.area
					}))
				}
			}
			
			resolve({
				provinceData,
				cityArray: cityArrayData
			})
		})
	}

	// 查找索引
	const findIndex = (arr, name) => {
		return arr?.findIndex(item => item.name === name) ?? -1
	}
</script>

<style lang="scss">
	.form-item-picker {
		width: 100%;
		height: 60rpx;
		position: relative !important;

		.region-value {
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
			height: 60rpx;
			line-height: 60rpx;
			font-size: 28rpx;
		}
	}
</style>
